package com.stephen.redisdemo.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * FutureTask这个类实现了RunnableFuture接口,而RunnableFuture接口实现了Runnable接口
 * 可以直接放在线程的构造方法中
 */
@Slf4j
public class FutureTaskDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> task = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println(Thread.currentThread().getName() + "\t come in callable");
                return 1024;
            }
        });

        /**
         * 若有多个线程,但使用的是同一个task,则只会调用一次
         */
        new Thread(task,"t1").start();
        new Thread(task,"t2").start();
        if (task.isDone()) { // 判断是否完成futureTask
            System.out.println("task result: " + task.get()); // 1024
        }
        System.out.println(Runtime.getRuntime().availableProcessors());

    }
}
